#include "stdafx.h"
#include "SQLConnection.h"

namespace AirCrash { 
namespace Calypso {

QSqlDatabase SQLConnection::mDb;

SQLConnection::SQLConnection() {
}

SQLConnection::~SQLConnection() {
}

bool SQLConnection::createDB() {
	if (Config::get("Simulation", "enabled").toBool()) {
		QFile::remove("database.db");
	}

	qDebug() << "Open DB";
	mDb = QSqlDatabase::addDatabase("QSQLITE");
	mDb.setDatabaseName("database.db");
	mDb.open();

	if (!mDb.isOpen()) {
		QMessageBox::warning(0, "Geen database", "Kan niet connecteren met de database.\nError: " + mDb.lastError().text());
		return false;
	}

	qDebug() << "Tables: " << mDb.tables();

	if (mDb.tables().size() == 0) {
		qDebug() << "Create Tables";

		QSqlQuery sql;

		sql.exec("CREATE TABLE Codes ("
				"Id integer primary key,"
				"ItemId integer,"
				"Day integer)");
		sql.exec("CREATE TABLE Items ("
				"Id integer primary key,"
				"Summary nvarchar(250),"
				"Image blob,"
				"Jackpot boolean,"
				"Friday integer,"
				"Saturday integer,"
				"Sunday integer,"
				"Rotate integer DEFAULT 0)");
		sql.exec("CREATE TABLE Scanned ("
				"Id integer primary key,"
				"Code integer,"
				"Date varchar(19))");
	}

	QSqlQuery checkItems("SELECT * FROM Items");
	if (!checkItems.record().contains("Rotate")) {
		qDebug() << "Add Rotate to the db";
		checkItems.exec("ALTER TABLE Items ADD COLUMN Rotate integer DEFAULT 0");
	}
	return true;
}

void SQLConnection::destroyDB() {
	mDb.close();
}

}
}